#!/bin/bash

case $1 in
    local)
        echo 'build local'
        source ./config_local.sh
        ;;
    staging)
        echo 'build staging'
        source ./config_staging.sh
        ;;
    production)
        echo 'build production'
        source ./config_production.sh
        ;;
    *)
        echo 'usage ./build.sh local|staging|production'
        exit 1
        ;;
esac

cd ..

wget https://mirrors.aliyun.com/composer/composer.phar -O /usr/local/bin/composer
chmod a+x /usr/local/bin/composer
composer u -o -vvv --no-dev

composer install
if [ $? -ne 0 ]; then
  	echo "Error: composer install."
  	exit 1
fi

if [ ! -f ./.env ]; then
    echo ".env file is not found, create .env"
    cp ./.env.example ./.env

    php artisan key:generate

    composer update
    if [ $? -ne 0 ]; then
      	echo "Error: composer update."
      	exit 1
    fi

    sed -i -e "s/APP_ENV=.*/APP_ENV=$APP_ENV/" ./.env
    sed -i -e "s/APP_DEBUG=.*/APP_DEBUG=$APP_DEBUG/" ./.env

    sed -i -e "s/DB_DATABASE=.*/DB_DATABASE=$DB/" ./.env
    sed -i -e "s/DB_USERNAME=.*/DB_USERNAME=$DB_USERNAME/" ./.env
    sed -i -e "s/DB_PASSWORD=.*/DB_PASSWORD=$DB_PASSWORD/" ./.env

    sed -i -e "s/BACKEND_DOMAIN=.*/BACKEND_DOMAIN=$BACKEND_DOMAIN/" ./.env
    sed -i -e "s/SELLER_DOMAIN=.*/SELLER_DOMAIN=$SELLER_DOMAIN/" ./.env
    sed -i -e "s/STORE_DOMAIN=.*/STORE_DOMAIN=$STORE_DOMAIN/" ./.env
    sed -i -e "s/FRONTEND_DOMAIN=.*/FRONTEND_DOMAIN=$FRONTEND_DOMAIN/" ./.env
    sed -i -e "s/MOBILE_DOMAIN=.*/MOBILE_DOMAIN=$MOBILE_DOMAIN/" ./.env
    sed -i -e "s/PUSH_DOMAIN=.*/PUSH_DOMAIN=$PUSH_DOMAIN/" ./.env

    sed -i -e "s/API_DOMAIN=.*/API_DOMAIN=$API_DOMAIN/" ./.env
	  sed -i -e "s/DEBUGBAR_ENABLED=.*/DEBUGBAR_ENABLED=$DEBUGBAR_ENABLED/" ./.env

    echo '' >> ./.env

    php artisan migrate
    if [ $? -ne 0 ]; then
	  	echo "Error: php artisan migrate."
	  	exit 1
	  fi

fi

# 导入sql
# 注意：如果是在 Windows 操作系统安装，需注释以下的导入sql脚本，然后在宝塔面板-数据库-导入， 手动导入 `/database/b2b2c.sql`
mysql -u$DB_USERNAME -p$DB_PASSWORD $DB < ./database/b2b2c.sql
if [ $? -ne 0 ]; then
	echo "Error: 导入sql失败."
	exit 1
fi

# 安装前端依赖
npm install
if [ $? -ne 0 ]; then
	echo "Error: npm install."
	exit 1
fi

# 拷贝js、css
npm run prod
if [ $? -ne 0 ]; then
	echo "Error: npm run prod-combine."
	exit 1
fi